<template>
  <div class="user-profile-container">
    <!-- 页面主体容器 -->
    <el-container class="main-container">
      <!-- 主要内容区域 -->
      <el-main class="main-content">
        <!-- 用户信息卡片 -->
        <el-card class="user-info-card shadow-hover">
          <el-row :gutter="30">
            <el-col :span="5">
              <div class="avatar-wrapper">
                <el-avatar
                  shape="circle"
                  :size="160"
                  :src="user.avatar || urlImg"
                  class="user-avatar"
                >
                  <i slot="icon" class="el-icon-user"></i>
                </el-avatar>
              </div>
            </el-col>
            <el-col :span="19">
              <el-descriptions title="用户信息" :column="3" class="user-descriptions">
                <el-descriptions-item label="用户名">{{ user.userName }}</el-descriptions-item>
                <el-descriptions-item label="昵称">{{ user.nickName }}</el-descriptions-item>
                <el-descriptions-item label="手机号">{{ user.phonenumber }}</el-descriptions-item>
                <el-descriptions-item label="邮箱">{{ user.email }}</el-descriptions-item>
                <el-descriptions-item label="性别">{{ user.sex | formatSex }}</el-descriptions-item>
                <el-descriptions-item label="备注">
                  <el-tag size="small" type="success">{{ user.remark || '无备注' }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="联系地址" :span="3">
                  {{ user.address || '未填写地址' }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </el-card>

        <!-- 功能快捷导航 -->
        <el-card class="function-nav shadow-hover">
          <el-row :gutter="20" class="nav-items">
            <el-col :span="4" v-for="(item, index) in functionItems" :key="index">
              <el-card class="nav-item" :body-style="{ padding: '0px' }">
                <div class="item-content" @click="handleItemClick(item)">
                  <div class="item-icon">
                    <i :class="item.icon"></i>
                  </div>
                  <div class="item-text">
                    <div class="item-title">
                      {{ item.title }}
                      <!-- 红点容器：当 count > 0 时显示 -->
                      <span class="red-dot" v-if="item.count && item.count > 0">
                        {{ item.count }}
                      </span>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-card>

        <!-- 购物车区域 -->
        <el-card class="shopping-cart shadow-hover">
          <div class="card-header">
            <h3 class="section-title">
              <i class="el-icon-shopping-cart-2 mr-2"></i>
              购物车
            </h3>
          </div>

          <!-- 新增全选控制栏 -->
          <div class="cart-select-all">
            <el-checkbox
              v-model="isAllChecked"
              @change="toggleAllCheck"
            >
              全选所有商品
            </el-checkbox>
            <span class="selected-count">
              已选择 {{ selectedItems.length }} 件商品
            </span>
          </div>

          <el-collapse v-model="activeMerchant" accordion class="merchant-list">
            <el-collapse-item
              v-for="(group, index) in shoppingCart"
              :key="index"
              :name="group.name"
            >
              <template #title>
                <div class="merchant-header">
                  <el-checkbox
                    v-model="group.isAllChecked"
                    @change="toggleGroupCheck(group)"
                  >
                    {{ group.name }}
                  </el-checkbox>
                  <span class="item-count">共{{ group.data.length }}件商品</span>
                </div>
              </template>
              <el-table
                :data="group.data"
                stripe
                border
                size="small"
                class="cart-table"
              >
                <el-table-column label="选择" width="60">
                  <template #default="scope">
                    <el-checkbox
                      v-model="scope.row.checked"
                      @change="updateSelectedItems"
                    ></el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column label="商品信息" width="600">
                  <template #default="scope">
                    <el-row :gutter="20" class="align-middle py-3">
                      <el-col :span="4">
                        <div class="product-image">
                          <img :src="scope.row.image" alt="商品图" class="product-image-img">
                        </div>
                      </el-col>
                      <el-col :span="20">
                        <div class="product-info">
                          <h4 class="product-name">{{ scope.row.productName }}</h4>
                          <p class="product-desc text-gray-500">{{ scope.row.description }}</p>
                          <div class="price-info mt-2">
                            <span class="price">¥{{ scope.row.price.toFixed(2) }}</span>
                            × {{ scope.row.number }}
                            <span class="subtotal text-danger ml-4">
                              小计: ¥{{ (scope.row.price * scope.row.number).toFixed(2) }}
                            </span>
                          </div>
                          <div class="sku-info text-sm text-gray-500">SKU: {{ scope.row.skuCode }}</div>
                        </div>
                      </el-col>
                    </el-row>
                  </template>
                </el-table-column>
              </el-table>
            </el-collapse-item>
          </el-collapse>

          <!-- 新增结算栏 -->
          <div class="cart-footer">
            <div class="cart-summary">
              <span class="total-price">
                总计: <span class="price-amount">¥{{ calculateTotalPrice().toFixed(2) }}</span>
              </span>
            </div>
            <el-button
              type="primary"
              size="large"
              @click="batchCheckout"
              :disabled="selectedItems.length === 0"
            >
              结算选中商品
            </el-button>
          </div>
        </el-card>

        <!-- 地址管理区域 -->
        <el-card class="address-card shadow-hover">
          <div class="card-header">
            <h3 class="section-title">
              <i class="el-icon-location mr-2"></i>
              收货地址
            </h3>
            <el-button
              type="primary"
              size="small"
              @click="dialogVisible = true"
              class="add-address-btn"
            >
              <i class="el-icon-plus mr-1"></i>添加新地址
            </el-button>
          </div>
          <el-table
            :data="userAddress"
            stripe
            border
            size="small"
            class="address-table mt-4"
          >
            <el-table-column prop="name" label="姓名" width="120" align="center"></el-table-column>
            <el-table-column prop="phonenumber" label="手机号" width="180" align="center"></el-table-column>
            <el-table-column prop="address" label="详细地址" align="center"></el-table-column>
            <el-table-column label="操作" width="120" align="center">
              <template #default="scope">
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-edit"
                  @click="handleEdit(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-main>
    </el-container>

    <!-- 地址编辑弹窗 -->
    <el-dialog
      title="管理收货地址"
      :visible.sync="dialogVisible"
      width="50%"
      class="custom-dialog"
      :before-close="handleClose"
    >
      <Address :userId="userId" :address="editAddress" @close="handleDialogClose"/>
    </el-dialog>

    <!-- 商品详情弹窗 -->
    <el-dialog
      :visible.sync="dialogVisible2"
      class="custom-dialog"
      :modal="false"
    >
      <check-product-info :id="id" :userId="userId" @close="handleDialogClose"/>
    </el-dialog>


    <el-dialog
      title=""
      :visible.sync="dialogVisible3"
      width="80%"
      class="custom-dialog"
      :modal="false"
    >
      <order-list @close="dialogVisible3=false"/>
    </el-dialog>

  </div>
</template>

<script>
import { getInfo, getShoppingCart, getAddress } from '@/api/list/user'
import Address from '@/views/list/user/address.vue'
import Info from '@/views/list/products/info.vue'
import Products from '@/views/list/products/products.vue'
import CheckProductInfo from '../products/checkproductinfo.vue'
import OrderList from '../products/orderList.vue'

export default {
  name: 'UserCenter',
  components: { OrderList, CheckProductInfo, Products, Address, Info },
  props: {
    userId: {
      type: Number,
      required: true
    }
  },
  filters: {
    formatSex(value) {
      const sexMap = { '0': '男', '1': '女', '2': '未知' }
      return sexMap[value] || '未知'
    }
  },
  data() {
    return {
      urlImg: 'https://picsum.photos/200/200',
      user: {},
      shoppingCart: [],
      userAddress: [],
      dialogVisible: false,
      dialogVisible2: false,
      dialogVisible3: false,
      activeMerchant: [],
      editAddress: null,
      unpayCount: 1,
      receiveCount: 4,
      commentCount: 6,
      id: null,
      isAllChecked: false,
      // 功能导航配置
      functionItems: [
        {
          title: '已取消',
          icon: 'el-icon-close',
          action: () => {
          },
          count: 2,
          status: 6
        },
        {
          title: '待付款',
          icon: 'el-icon-money',
          action: () => {
          },
          count: 5,
          status: 1
        },
        {
          title: '待收货',
          icon: 'el-icon-truck',
          action: () => {
          },
          count: 6,
          status: 4
        },
        {
          title: '待评价',
          icon: 'el-icon-message',
          action: () => {
          },
          count: 3,
          status: 5
        },
        {
          title: '已支付',
          icon: 'el-icon-check',
          action: () => {
          },
          count: 5,
          status: 2
        }
      ]
    }
  },
  computed: {
    totalItems() {
      return this.shoppingCart.reduce((acc, group) => acc + group.data.length, 0)
    },
    selectedItems() {
      return this.shoppingCart.flatMap(group =>
        group.data.filter(item => item.checked)
      )
    }
  },
  mounted() {
    this.fetchData()
  },
  watch: {
    userId(newVal) {
      if (newVal) this.fetchData()
      this.dialogVisible = false
      this.dialogVisible2 = false
    }
  },
  methods: {
    handleItemClick(item) {
      this.dialogVisible3 = true
      // 1. 获取当前项的 count 值
      const count = item.status

      // 2. 执行自定义逻辑（示例）
      console.log(`点击了 ${item.status}，count 值为：`, count)

      // 3. 如需保留原有 action 回调，可手动触发
      item.action && item.action()
    },
    async fetchData() {
      try {
        const [userInfo, cartData, addressData] = await Promise.all([
          getInfo(this.userId),
          getShoppingCart(this.userId),
          getAddress(this.userId)
        ])

        this.user = userInfo.data
        // 处理购物车数据，添加选中状态
        this.shoppingCart = cartData.data.map(group => ({
          ...group,
          isAllChecked: false,
          data: group.data.map(item => ({
            ...item,
            checked: false
          }))
        }))
        this.userAddress = addressData.data

        // 模拟统计数据（需根据实际接口调整）
        this.unpayCount = Math.floor(Math.random() * 10)
        this.receiveCount = Math.floor(Math.random() * 5)
        this.commentCount = Math.floor(Math.random() * 3)
      } catch (error) {
        console.error('数据获取失败:', error)
        this.$message.error('加载用户信息失败')
      }
    },

    toggleAllCheck() {
      this.shoppingCart.forEach(group => {
        group.isAllChecked = this.isAllChecked
        group.data.forEach(item => {
          item.checked = this.isAllChecked
        })
      })
    },

    toggleGroupCheck(group) {
      group.data.forEach(item => {
        item.checked = group.isAllChecked
      })
      this.updateAllCheckedStatus()
    },

    updateSelectedItems() {
      // 更新商家分组的全选状态
      this.shoppingCart.forEach(group => {
        group.isAllChecked = group.data.every(item => item.checked)
      })
      this.updateAllCheckedStatus()
    },

    updateAllCheckedStatus() {
      this.isAllChecked = this.shoppingCart.every(group =>
        group.isAllChecked && group.data.length > 0
      )
    },

    calculateTotalPrice() {
      return this.selectedItems.reduce((total, item) => {
        return total + (item.price * item.number)
      }, 0)
    },

    batchCheckout() {
      if (this.selectedItems.length === 0) {
        this.$message.warning('请选择要结算的商品')
        return
      }

      const productIds = this.selectedItems.map(item => item.id)
      console.log('结算商品ID:', productIds)

      // 这里调用结算接口
      this.$message.success(`已提交 ${this.selectedItems.length} 件商品进行结算`)

      // 结算成功后可以清空购物车或刷新数据
      // this.fetchData()
    },

    handleEdit(address) {
      this.editAddress = { ...address }
      this.dialogVisible = true
    },

    handleDelete(address) {
      this.$confirm('确认删除该地址吗？', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 调用删除接口
        await this.$api.deleteAddress(address.id)
        this.fetchData()
        this.$message.success('地址删除成功')
      })
    },

    handleDialogClose() {
      this.dialogVisible = false
      this.dialogVisible2 = false
      this.editAddress = null
      this.fetchData()
    },

    handleClose(done) {
      this.$confirm('是否保存当前修改？', '提示', {
        confirmButtonText: '保存',
        cancelButtonText: '放弃',
        type: 'question'
      }).then(() => {
        // 保存逻辑
        done()
      }).catch(() => {
        done()
      })
    }
  }
}
</script>

<style scoped lang="scss">
.user-profile-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.main-container {
  max-width: 1200px;
  margin: 0 auto;
  background-color: white;
}

.header {
  height: 60px !important;
  background-color: #409eff;
  color: white;
  line-height: 60px;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.logo {
  font-size: 1.5rem;
  font-weight: bold;
}

.nav-menu {
  border-bottom: none;
  background-color: transparent;
  color: white;

  .el-menu-item {
    color: white !important;
  }
}

.main-content {
  padding: 20px;
  min-height: calc(100vh - 120px);
}

.user-info-card, .function-nav, .shopping-cart, .address-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  }
}

.avatar-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
}

.user-avatar {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;

  &:hover {
    transform: scale(1.05);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
  }
}

.user-descriptions {
  font-size: 1.1rem;

  .el-descriptions-item {
    padding: 8px 0;
  }
}

.function-nav {
  padding: 15px;
}

.nav-items {
  display: flex;
  justify-content: space-between;
}

.nav-item {
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
  }
}

.item-content {
  padding: 20px 10px;
  text-align: center;
}

.item-icon {
  font-size: 2rem;
  margin-bottom: 10px;
}


.item-count {
  margin-top: 5px;
  font-size: 0.9rem;
  color: #ff4949;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;

  i {
    font-size: 1.2rem;
    margin-right: 8px;
  }
}

.add-address-btn {
  display: flex;
  align-items: center;
}

.merchant-list {
  .el-collapse-item__header {
    padding: 16px;
    font-size: 1.1rem;
    background-color: #f8f9fa;
    border-radius: 8px;
    margin-bottom: 12px;
  }
}

.cart-table {
  .el-table__row {
    transition: all 0.2s ease;

    &:hover {
      background-color: #f0f5ff;
    }
  }

  .product-image {
    width: 70px;
    height: 70px;
    overflow: hidden;
    border-radius: 8px;
    position: relative; /* 确保子元素定位正常 */
  }

  .product-image-img {
    width: 100%; /* 撑满容器宽度 */
    height: 100%; /* 撑满容器高度 */
    object-fit: cover; /* 等比例缩放，裁剪超出部分 */
  }

  .product-name {
    font-size: 1.1rem;
    font-weight: 500;
    margin-bottom: 4px;
  }

  .product-desc {
    color: #666;
    font-size: 0.9rem;
    line-height: 1.6;
  }

  .price-info {
    margin-top: 8px;
    font-size: 1.1rem;
    color: #333;

    .price {
      color: #409eff;
      font-weight: 600;
    }

    .subtotal {
      color: #ff4949;
      font-weight: 500;
    }
  }
}

.footer {
  height: 60px !important;
  background-color: #f8f9fa;
  color: #606266;
  display: flex;
  align-items: center;
  justify-content: center;
}

.footer-content {
  text-align: center;
}

.footer-links {
  margin-top: 5px;

  a {
    margin: 0 10px;
    color: #606266;
    text-decoration: none;
  }
}

/* 新增购物车相关样式 */
.cart-select-all {
  padding: 15px 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.selected-count {
  color: #606266;
  font-size: 14px;
}

.cart-footer {
  padding: 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f8f9fa;
  margin-top: 15px;
  border-radius: 0 0 8px 8px;
}

.cart-summary {
  display: flex;
  align-items: center;
}

.total-price {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.price-amount {
  color: #ff4949;
  font-size: 18px;
  margin-left: 5px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .main-container {
    width: 100%;
    margin: 0;
    border-radius: 0;
  }

  .el-descriptions {
    column: 2;
  }

  .functionItems {
    flex-wrap: wrap;

    .el-col {
      flex-basis: 50% !important;
      max-width: 50% !important;
      margin-bottom: 15px;
    }
  }

  .cart-footer {
    flex-direction: column;
    gap: 15px;
  }

  .cart-summary {
    width: 100%;
    justify-content: center;
  }
}

.red-dot {
  /* 定位：相对于标题容器绝对定位 */
  position: absolute;
  top: -50px; /* 向上偏移，调整红点位置 */
  right: -6px; /* 向右偏移 */
  /* 尺寸与背景 */
  width: 18px;
  height: 18px;
  line-height: 18px; /* 文字垂直居中 */
  border-radius: 50%; /* 圆形 */
  background-color: #ff4949; /* 红色 */
  color: #fff; /* 文字颜色 */
  font-size: 10px; /* 字体大小 */
  text-align: center; /* 文字水平居中 */
  /* 防止超出容器 */
  z-index: 1;
  min-width: 18px; /* 最小宽度 */
  padding: 0 4px; /* 左右内边距，适应长数字 */
  animation: bounce 0.5s ease infinite; /* 闪烁动画 */
}

@keyframes bounce {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
}

/* 优化标题容器的定位，作为红点的参考基准 */
.item-title {
  position: relative; /* 为红点提供定位参考 */
  display: inline-block; /* 确保标题不为块级元素，避免红点位置偏移 */
}
</style>
